import axios from 'axios';
import type { LoginRequest, LoginResponse } from './types';

// 创建axios实例
const authApi = axios.create({
  baseURL: import.meta.env.VITE_BASE_API+"/api/v1",
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 登录接口
export const login = async (data: LoginRequest): Promise<LoginResponse> => {
  try {
    const response = await authApi.post<LoginResponse>('/users/login', data);
    // 登录成功后保存token
    if (response.data.code === 0) {
      const { access_token, expires_at } = response.data.data;
      localStorage.setItem('access_token', access_token);
      localStorage.setItem('token_expires_at', expires_at.toString());
    }
    return response.data;
  } catch (error) {
    throw error;
  }
};

// 获取保存的token
export const getToken = (): string | null => {
  console.log(localStorage.getItem('access_token'))
  return localStorage.getItem('access_token');
};

// 清除token
export const clearToken = (): void => {
  localStorage.removeItem('access_token');
  localStorage.removeItem('token_expires_at');
};

// 检查token是否过期
export const isTokenExpired = (): boolean => {
  const expiresAt = localStorage.getItem('token_expires_at');
  if (!expiresAt) return true;
  
  const expiresTime = parseInt(expiresAt);
  return Date.now() >= expiresTime;
};